#! -*- coding: utf-8 -*-

from script_utils import query, oid2nid
from script_utils import models

cols = {
    "deviceid_cols": [
        "id",
        "device_id",
        "device",
        "name",
        "name",
        "tel",
        "consultation_date",
        "source",
        "last_modified",
        "date_added"
    ],
    "statistics": [
        "id",
        "device_id",
        "category",
        "date_added",
    ],
    "user_device_token": [
        "id",
        "user_id",
        "device",
        "token",
        "is_active",
        "date_added",
    ],
    "device_token": [
        "id",
        "device_token",
        "date_added",
        "device",
        "is_active",
        "last_registed",
        "breadtrip_version",
    ]
}


def migrate_deviceid():
    for row in query('vacation_deviceid', cols=cols['deviceid_cols']):
        obj = dict(zip(cols['deviceid_cols'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_deviceid"][oid]
        models.DeviceId.objects.create(**obj)


def migrate_statistics():
    deviceid = oid2nid["vacation_deviceid"]
    for row in query('vacation_statistics', cols=cols['statistics']):
        obj = dict(zip(cols['statistics'], row))
        oid = obj['id']
        obj['id'] = oid2nid["vacation_statistics"][oid]
        obj['device'] = deviceid[obj['device_id']]
        del obj['device_id']
        models.Statistics.objects.create(**obj)


def migrate_user_device_token():
    id_dict = oid2nid["btmisc_userdevicetoken"]
    for row in query('btmisc_userdevicetoken', cols=cols['user_device_token']):
        obj = dict(zip(cols['user_device_token'], row))
        oid = obj['id']
        obj['id'] = id_dict[oid]
        models.UserDeviceToken.objects.create(**obj)


def migrate_device_token():
    for row in query('btmisc_devicetoken', cols=cols['device_token']):
        obj = dict(zip(cols['device_token'], row))
        oid = obj['id']
        obj['id'] = oid2nid["btmisc_devicetoken"][oid]
        models.DeviceToken.objects.create(**obj)


if __name__ == "__main__":
    print 'migrate vacation_deviceid start...'
    migrate_deviceid()
    print 'migrate vacation_deviceid end...'

    print 'migrate vacation_statistics start...'
    migrate_statistics()
    print 'migrate vacation_statistics end...'

    print "migrate_user_device_token ..."
    migrate_user_device_token()
    print "migrate_user_device_token ..."

    print "migrate_device_token ..."
    migrate_device_token()
    print "migrate_device_token ..."
